import collections


class Solution(object):
    def deleteTreeNodes(self, nodes, parent, value):
        """
        :type nodes: int
        :type parent: List[int]
        :type value: List[int]
        :rtype: int
        """
        d = collections.defaultdict(set)
        for i in range(nodes):
            d[parent[i]].add(i)
        root = -1
        def search(node):
            if not d[node]:
                if value[node] == 0:
                    return 0, 0
                else:
                    return 1, value[node]
            else:
                child_count = 1
                child_value = value[node]
                for child in d[node]:
                    now_count, now_value = search(child)
                    child_count += now_count
                    child_value += now_value
                if child_value == 0:
                    return 0, 0
                else:
                    return child_count, child_value

        return search(d[root].pop())[0]


data = Solution()
nodes = 7
parent = [-1, 0, 0, 1, 2, 2, 2]
value = [1, -2, 4, 0, -2, -1, -1]
print(data.deleteTreeNodes(nodes, parent, value))
nodes = 3
parent = [-1, 0, 0]
value = [-2, -2, 4]
print(data.deleteTreeNodes(nodes, parent, value))
nodes = 7
parent = [-1,0,0,1,2,2,2]
value = [1,-2,4,0,-2,-1,-2]
print(data.deleteTreeNodes(nodes, parent, value))
nodes = 5
parent = [-1,0,1,0,0]
value = [-672,441,18,728,378]
print(data.deleteTreeNodes(nodes, parent, value))
nodes = 5
parent = [-1,0,0,1,1]
value = [-686,-842,616,-739,-746]
print(data.deleteTreeNodes(nodes, parent, value))

